/*
 * Created on Jun 14, 2006
 * 
 */

package com.probiz.estore.common.helper;

import java.util.List;
import java.util.Map;

import net.sf.navigator.menu.MenuComponent;

/**
 * <p>
 * Note: To parse and display current menu correctly, menu structure and url
 * structure must be orginized in the same style. However the directory where
 * the page is in is not important, we decide everything by parsing the url
 * structure. Every submenu should has its own url structure, which is exactly
 * the same as menu structure, or else, this program will return the incorrect
 * parent menu. And Menu must define url/page, and the URL must be unique. The
 * first menu must be home page.
 * </p>
 * 
 * @author Legend
 * 
 */
public class MenuHelper {
   
	/**
	 * 根据当前的url选中对应的menu。
	 * @param menu
	 * @param requestUrl
	 */
	public static boolean getSelectedMenuMap(Map<String, String> selectedMenuMap, MenuComponent menu, final String requestUrl)
	{
		//首先看是否匹配url中的模块名，不带模块名的
		if (isModulePathMatched(menu, requestUrl) || (requestUrl.indexOf("/", 1)==-1) ) {
			//看看menu下的子菜单是否有与父菜单url配置相同的菜单
			MenuComponent menuMatched = getSubMenuMatched(menu, requestUrl);
			if(menuMatched==null)
				menuMatched = menu;
				
			
			//自下而上设置菜单被选中
			do{
	    		selectedMenuMap.put(menuMatched.getName(), "selected");
	    		menuMatched = menuMatched.getParent();
			}while(menuMatched!=null);
	    	
	    	return true;
		}else{
			List<MenuComponent> sub = menu.getComponents();
			for (int i = 0; sub != null && i < sub.size(); i++) {
				if(getSelectedMenuMap(selectedMenuMap, sub.get(i), requestUrl))
					return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 获取匹配requestUrl的最底层的子菜单
	 */
	private static MenuComponent getSubMenuMatched(MenuComponent subMenu, final String requestUrl){
		List<MenuComponent> sublist = subMenu.getComponents();
		MenuComponent targetSubMenu = null;
		int firstMatched = 0;
		for (int i = 0; sublist != null && i < sublist.size(); i++) {
			MenuComponent tempSubMenu = sublist.get(i);
			if( tempSubMenu.getComponents()!=null && tempSubMenu.getComponents().size()>0){
				targetSubMenu = getSubMenuMatched(tempSubMenu, requestUrl);
				if(targetSubMenu!=null) 
					break;
			}else{
				int matchedReturn = isMatchedParentMenuForUrl(tempSubMenu, requestUrl);
				//第一次对比成功或精确查找到，则标记被选中的菜单
				if((firstMatched==0 && matchedReturn==1) || matchedReturn==2){
					targetSubMenu = tempSubMenu;
					//精确查找到
					if(matchedReturn==2)
						break;
					
					firstMatched = matchedReturn;
				} 
			}
		}
		
		return targetSubMenu;
	}
	
	private static String getParentLevelUrl(final String url) {
		String parsedUrl = removeParamsFromUrl(url);
		int idx = url.indexOf(".");
		if (idx > 0) {
			int idx2 = url.lastIndexOf("/");
			parsedUrl = url.substring(0, idx2);
		}

		return parsedUrl;
	}

	/**
	 * url中的模块名路径是否匹配
	 * @param menu
	 * @param uri
	 * @return
	 */
	private static boolean isModulePathMatched(final MenuComponent menu, final String uri){
		if(menu.getPage()==null) return false;
		//是否包含模块名，如"/customer/membership.html"模块名为customer; "/index.html"没有模块名
		int menuModuleIdx = menu.getPage().indexOf("/", 1);
		int urlModuleIdx = uri.indexOf("/", 1);
		if(menuModuleIdx==-1 || urlModuleIdx==-1)
			return false;
		//获取menu url中的模块名，如/customer/membership.html获取的是  /customer/
		String menuModulePath = menu.getPage().substring(0, menuModuleIdx+1);
		String uriModulePath = uri.substring(0, urlModuleIdx+1);
		
		return menuModulePath.equals(uriModulePath);
	}
	
	/**
	 * 菜单menu-config中配置的page项值是否与请求的URI匹配
	 * @param menu
	 * @param requestUrl  URI
	 * @return
	 * <p>0 - 不匹配</p>
	 * <p>1 - 匹配，如匹配字符串"/customer/membership.html"</p>
	 * <p>2 - 精确匹配 doAction参数也匹配，如匹配字符串"/customer/membership.html?doAction=add</p>
	 */
	private static int isMatchedParentMenuForUrl(final MenuComponent menu,
			final String requestUrl) {
		if(null == menu || null == menu.getPage())return 0;
		if(requestUrl.startsWith(menu.getPage())){
			//若menu url有参数，则代表精确匹配，这里不太严格，以后需要可以调整如判断是否有doAction参数
			if(menu.getPage()!=null && menu.getPage().indexOf("?")!=-1)
				return 2;
			return 1;
		}
		
		String menuUrl = removeParamsFromUrl(menu.getPage());
		if(requestUrl.startsWith(menuUrl)){
			return 1;
		}
		
	    return 0;
	}

	private static boolean isMenuUrlMatchCustom(final String url1,
			final String url2) {

		String menuUrl = removeParamsFromUrl(url1).toLowerCase();
		String parsedRequestUrl = removeParamsFromUrl(url2).toLowerCase();

		// -----------
		int idx = menuUrl.indexOf(".");
		if (idx > 0) {
			int idx2 = menuUrl.lastIndexOf("/");
			if (idx2 == -1)
				idx2 = 0;
			menuUrl = menuUrl.substring(idx2 + 1, idx - 1);
			if (menuUrl.length() > 1) {
				menuUrl = menuUrl.substring(0, menuUrl.length()) + "_";

			}

			if (parsedRequestUrl.lastIndexOf("/") != -1)
				parsedRequestUrl = parsedRequestUrl.substring(parsedRequestUrl
						.lastIndexOf("/") + 1);
		}

		// System.err.println("---custom---------menuUrl-------"+menuUrl);
		// System.err.println("---custom---------parsedRequestUrl-------"+parsedRequestUrl);
		return (parsedRequestUrl.startsWith(menuUrl));
	}

	private static boolean isMenuUrlMatched(final String url1, final String url2) {
		String uri1 = removeParamsFromUrl(url1);
		String uri2 = removeParamsFromUrl(url2);

		if (uri1.equals(uri2)) {
			return true;
		}

		return false;
	}

	private static boolean isMenuUrlMatchEdit(final String url1,
			final String url2) {

		String menuUrl = removeParamsFromUrl(url1).toLowerCase();
		String parsedRequestUrl = removeParamsFromUrl(url2).toLowerCase();

		// -----------
		int idx = menuUrl.indexOf(".");
		if (idx > 0) {
			int idx2 = menuUrl.lastIndexOf("/");
			if (idx2 == -1)
				idx2 = 0;
			menuUrl = menuUrl.substring(idx2 + 1, idx - 1);
			if (menuUrl.length() > 1) {
				if (!menuUrl.startsWith("edit"))
					menuUrl = "edit" + menuUrl.substring(0, menuUrl.length());
				else
					menuUrl = menuUrl.substring(0, menuUrl.length());
			}

		}
		int idx3 = parsedRequestUrl.indexOf(".");
		if (idx3 > 0) {
			int idx4 = parsedRequestUrl.lastIndexOf("/");
			if (idx4 == -1)
				idx4 = 0;
			parsedRequestUrl = parsedRequestUrl.substring(idx4 + 1, idx3);
			if (parsedRequestUrl.length() > 1) {
				parsedRequestUrl = parsedRequestUrl.substring(0,
						parsedRequestUrl.length());

			}

		}
		// System.err.println("---edit---------menuUrl-------"+menuUrl);
		// System.err.println("---edit---------parsedRequestUrl-------"+parsedRequestUrl);
		return (parsedRequestUrl.equals(menuUrl));
	}

	private static String removeParamsFromUrl(final String url) {
		int idx = url.indexOf("?");
		String parsedUrl = null;
		if (idx > 0) {
			parsedUrl = url.substring(0, idx);
		} else {
			parsedUrl = url;
		}

		if (parsedUrl.endsWith("/")) {
			parsedUrl = parsedUrl.substring(0, parsedUrl.length() - 1);
		}

		return parsedUrl;
	}

}
